<?php

namespace app\rent\controller;

use think\Controller;

class Lease extends Controller
{

  public function _initialize()
  {
    parent::_initialize();
    // 实例化模型   
    $this->BusinessModel = model('Business.Business');
    $this->LeaseModel = model('Lease');
    $this->ProductModel = model('Product.Product');
    $this->RecordModel = model('Business.Record');
    $this->ExpressqueryModel = model('Expressquery');
  }

  // 生成租赁订单
  public function add()
  {
    $busid = $this->request->param('busid', 0, 'trim');
    $proid = $this->request->param('proid', 0, 'trim');
    $params = $this->request->param();

    $Businessinfo = $this->BusinessModel->find($busid);

    if (!$Businessinfo) {
      $this->error('用户不存在');
    }

    $Productinfo = $this->ProductModel->find($proid);

    if (!$Productinfo) {
      $this->error('租赁商品不存在');
    }

    // 判断余额
    $money = bcsub($Businessinfo['money'], $params['price'], 2);
    if ($money < 0) {
      $this->error('余额不足，请去充值');
    }

    // 判断库存
    $stock = bcsub($Productinfo['stock'], 1);
    if ($stock < 0) {
      $this->error($Productinfo['name'] . '库存不足，请重新选择');
    }

    // 开启事务
    $this->BusinessModel->startTrans();
    $this->LeaseModel->startTrans();
    $this->ProductModel->startTrans();
    $this->RecordModel->startTrans();


    $LeaseData = [
      'busid' => $busid,
      'proid' => $proid,
      'rent' => $Productinfo['rent'],
      'price' => $params['price'],
      'endtime' => strtotime($params['endtime']),
      'address' => $params['address'],
      'province' => $params['province'],
      'city' => $params['city'],
      'district' => $params['district'],
      'status' => '1'
    ];

    if (isset($_FILES['card']) && $_FILES['card']['size'] > 0) {
      $res = upload('card');
      if ($res['code'] == 0) {
        $this->error($res['msg']);
      }
      $LeaseData['card'] = $res['data'];
    }

    // 租赁订单表 添加校验器
    $LeaseStatus = $this->LeaseModel->save($LeaseData);
    if ($LeaseStatus === false) {
      $this->error($this->LeaseModel->getError());
    }

    // 用户表余额更新
    $BusinessStatus = $this->BusinessModel->where('id', $busid)->update(['money' => $money]);
    if ($BusinessStatus === false) {
      $this->LeaseModel->rollback();
      $this->error($this->BusinessModel->getError());
    }

    // 产品表库存减少
    $ProductStatus = $this->ProductModel->where('id', $proid)->update(['stock' => $stock]);
    if ($ProductStatus === false) {
      $this->LeaseModel->rollback();
      $this->BusinessModel->rollback();
      $this->error($this->ProductModel->getError());
    }

    // 消费记录表新增
    $Recorddata = [
      'total' => $params['price'],
      'content' => "租赁: 【" . $Productinfo['name'] . "】商品花费了 ￥" . $params['price'] . " 元",
      'busid' => $busid,
      'state' => '4'
    ];

    $RecordStatus = $this->RecordModel->save($Recorddata);
    if ($RecordStatus === false) {
      $this->LeaseModel->rollback();
      $this->BusinessModel->rollback();
      $this->ProductModel->rollback();
      $this->error($this->RecordModel->getError());
    }

    if ($RecordStatus === false || $ProductStatus === false || $BusinessStatus === false || $LeaseStatus === false) {
      $this->LeaseModel->rollback();
      $this->BusinessModel->rollback();
      $this->ProductModel->rollback();
      $this->RecordModel->rollback();
      $this->error('租赁失败');
    } else {
      $this->LeaseModel->commit();
      $this->BusinessModel->commit();
      $this->ProductModel->commit();
      $this->RecordModel->commit();
      $this->success('租赁成功');
    }
  }

  // 订单列表
  public function index()
  {
    $busid = $this->request->param('busid', 0, 'trim');
    $status = $this->request->param('status', '', 'trim');
    $page = $this->request->param('page', 1, 'trim');
    $limit = $this->request->param('limit', 5, 'trim');

    $Businessinfo = $this->BusinessModel->find($busid);
    if (!$Businessinfo) {
      $this->error('用户不存在');
    }

    $where = [];

    if (!empty($status)) {
      $where['lease.status'] = $status;
    }

    // $data = $this->LeaseModel->with('product')->where($where)->order('createtime desc')->select();
    $data = $this->LeaseModel->with('product')->where($where)->order('createtime desc')->paginate($limit, true, ['page' => $page]);


    if (count($data) > 0) {
      $this->success('', '', $data);
    } else {
      $this->error('暂无数据');
    }
  }


  // 订单详情
  public function info()
  {
    $busid = $this->request->param('busid', 0, 'trim');
    $leaseid = $this->request->param('leaseid', 0, 'trim');

    $Businessinfo = $this->BusinessModel->find($busid);
    if (!$Businessinfo) {
      $this->error('用户不存在');
    }

    $data = $this->LeaseModel->with(['product', 'business'])->find($leaseid);

    if (!$data) {
      $this->error('订单不存在');
    }

    $this->success('', '', $data);
  }

  // 快递公司
  public function express()
  {
    $data = $this->ExpressqueryModel->field('id as value,name as text')->select();

    $this->success('', '', $data);
  }


  // 归还商品
  public function rcovery()
  {
    $busid = $this->request->param('busid', 0, 'trim');
    $leaseid = $this->request->param('leaseid', 0, 'trim');
    $expcode = $this->request->param('expcode', '', 'trim');
    $expid = $this->request->param('expid', 0, 'trim');

    $Businessinfo = $this->BusinessModel->find($busid);
    if (!$Businessinfo) {
      $this->error('用户不存在');
    }

    $data = $this->LeaseModel->find($leaseid);

    if (!$data) {
      $this->error('订单不存在');
    }

    $data = [
      'id' => $leaseid,
      'expcode' => $expcode,
      'expid' => $expid,
      'status' => '4'
    ];

    $result = $this->LeaseModel->isUpdate()->save($data);
    if ($result === false) {
      $this->error('归还失败');
    } else {
      $this->success('归还成功，待收货');
    }
  }

  // 商品评价
  public function rate()
  {
    $busid = $this->request->param('busid', 0, 'trim');
    $leaseid = $this->request->param('leaseid', 0, 'trim');
    $comment = $this->request->param('comment', '', 'trim');
    $rate = $this->request->param('rate', 0, 'trim');

    $Businessinfo = $this->BusinessModel->find($busid);
    if (!$Businessinfo) {
      $this->error('用户不存在');
    }

    $data = $this->LeaseModel->find($leaseid);

    if (!$data) {
      $this->error('订单不存在');
    }

    $data = [
      'id' => $leaseid,
      'comment' => $comment,
      'rate' => $rate,
      'status' => '6'
    ];

    $result = $this->LeaseModel->isUpdate()->save($data);
    if ($result === false) {
      $this->error('归还失败');
    } else {
      $this->success('归还成功，待收货');
    }
  }

  //确认收货
  public function leasereceive()
  {
    $busid = $this->request->param('busid', 0, 'trim');
    $leaseid = $this->request->param('leaseid', 0, 'trim');

    $Businessinfo = $this->BusinessModel->find($busid);
    if (!$Businessinfo) {
      $this->error('用户不存在');
    }
    $receive = $this->LeaseModel->where(['id' => $leaseid, 'busid' => $busid])
      ->update(['status' => '3']);
    if ($receive == false) {
      $this->error('收货失败');
    } else {
      $this->success('收货成功', '', $receive);
    }
  }

}
